﻿using Microsoft.Web.WebSockets;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using FServer.Models;

namespace FServer.Controllers
{
    public class WSHandler : WebSocketHandler
    {
        private NguoiDung currentUser;
        private static WebSocketCollection tvb_clients = new WebSocketCollection();

        public override void OnMessage(Byte[] message)
        {

        }

        public override void OnMessage(String message)
        {
            String StrCode = message.Substring(0, 5);

            switch(StrCode)
            {
                case "00001":
                    xuLyDangNhap(message.Substring(5,message.Length));
                    break;

                case "00002":
                    break;
            }
        }

        public override void OnClose()
        {
            tvb_clients.Remove(this);
        }

        public override void OnError()
        {

        }

        public override void OnOpen()
        {

        }

        public void xuLyDangNhap(String message)
        {
            String[] info = message.Split(',');

            NguoiDungDAO nddao = new NguoiDungDAO();
            currentUser = nddao.dangNhap(info[0], info[1]);

            if( currentUser != null)
            {
                tvb_clients.Add(this);
                this.Send("00001Đăng nhập thành công");
            }

            this.Send("00001Đăng nhập thất bại");
        }

        public void chat()
        {

        }
    }
}
